package com.stanwind.netty.core.protocol.codc;

import com.stanwind.netty.constant.ServerSetting;
import com.stanwind.netty.core.protocol.model.Response;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;

/**
 * 响应编码器
 *
 * @author StanWind
 */
public class ResponseEncoder extends OneToOneEncoder {
    //[4D 5A 00 00] [00 00 00 00] [LENGTH] [COMMAND] [DATA]
    @Override
    protected Object encode(ChannelHandlerContext context, Channel channel,
                            Object obj) throws Exception {
        // 获取一个动态buffer
        ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
        if (obj instanceof Response) {    //	如果是正常包对象
            Response response = (Response) (obj);
            // 开始写数据
            // 写包头
            buffer.writeInt(ServerSetting.FLAG);
            //写time
            buffer.writeInt(response.getTime());
            // length
            buffer.writeShort(response.getLength());
            // cmd
            buffer.writeShort(response.getCmd());
            // data
            if (response.getData() != null) {
                buffer.writeBytes(response.getData());
            }
        } else {
            buffer.writeBytes((byte[]) obj);
        }

        return buffer;
    }
}
